package com.piece.admin.config;

import com.piece.core.oauth.config.AuthorizationServerProvider;
import com.piece.core.oauth.config.CustomAuthorizationServerConfig;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import java.util.Comparator;
import java.util.List;

@Configuration
@EnableAuthorizationServer
@AutoConfigureAfter(AuthorizationServerEndpointsConfigurer.class)
public class UaaAuthorizationServerConfiguration extends CustomAuthorizationServerConfig implements InitializingBean {

    @Autowired(required = false)
    private List<AuthorizationServerProvider> providers;

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        super.configure(endpoints);

        if (null != providers) {
            for (AuthorizationServerProvider configurer : providers) {
                configurer.configure(endpoints);
            }
        }
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        super.configure(clients);

        if (null != providers) {
            for (AuthorizationServerProvider configurer : providers) {
                configurer.configure(clients);
            }
        }
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        super.configure(security);

        if (null != providers) {
            for (AuthorizationServerProvider configurer : providers) {
                configurer.configure(security);
            }
        }
    }

    @Override
    public void afterPropertiesSet() {
        if (null != providers) {
            providers.sort(Comparator.comparingInt(Ordered::getOrder));
        }
    }
}
